<template>
  <div class="subordinate-organization-container">
    <!-- 搜索和添加组织区域 -->
    <div class="bg-white p-4 rounded-t-lg">
      <div class="flex items-center justify-between">
        <div class="flex gap-2">
                     <el-input v-model="searchParams.organizationName" :placeholder="t('authority.subordinate.organizationName')" clearable
             :prefix-icon="Search" @input="debouncedSearch()" />
          <el-button type="primary" @click="handleSearch">{{ t('authority.common.search') }}</el-button>
        </div>
        <el-button 
          v-if="hasPermission('sys:suborganization:save') || isSuperAdmin"
          @click="handleAddOrg"
        >
          {{ t('authority.subordinate.addOrganization') }}
        </el-button>
      </div>
    </div>

    <!-- 组织列表表格 -->
    <div class="table-container bg-white p-4 rounded shadow-sm">
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="tableData.length > 0"
        @retry="retryFetch"
      >
        <div class="table-wrapper">
          <el-table 
            :data="tableData" 
            border 
            height="100%" 
            class="adaptive-table design-table"
            table-layout="auto"
            :header-cell-style="headerCellStyle"
          >
          <!-- 数据列 - 完全自适应宽度 -->
          <el-table-column 
            prop="organizationName" 
            :label="t('authority.subordinate.organizationName')" 
            min-width="150"
            class-name="data-column"
          />
          <el-table-column 
            prop="countryRegion" 
            :label="t('authority.subordinate.countryRegion')" 
            min-width="120"
            class-name="data-column"
          />
          <el-table-column 
            prop="organizationEmail" 
            :label="t('authority.subordinate.organizationEmail')" 
            min-width="180"
            class-name="data-column"
          />
          <el-table-column 
            prop="organizationType" 
            :label="t('authority.subordinate.organizationType')" 
            min-width="120"
            class-name="data-column"
          >
            <template #default="scope">
              <span v-if="scope.row.organizationType === 0">Zendure</span>
              <span v-else-if="scope.row.organizationType === 1">{{ t('role.installer') }}</span>
              <span v-else-if="scope.row.organizationType === 2">{{ t('role.distributor') }}</span>
              <span v-else-if="scope.row.organizationType === 3">Organization Client</span>
              <span v-else>{{ scope.row.organizationType }}</span>
            </template>
          </el-table-column>
          <el-table-column 
            prop="adminName" 
            :label="t('authority.subordinate.adminName')" 
            min-width="120"
            class-name="data-column"
          />
          <el-table-column 
            prop="createTime" 
            :label="t('authority.role.createTime')" 
            min-width="150"
            class-name="data-column"
          />
          <el-table-column 
            prop="modifyTime" 
            :label="t('authority.role.modifyTime')" 
            min-width="150"
            class-name="data-column"
          />
          <el-table-column 
            prop="modifyUser" 
            :label="t('authority.subordinate.modifyUser')" 
            min-width="120"
            class-name="data-column"
          />
          
          <!-- 操作列 - 固定宽度，始终在右侧 -->
          <el-table-column 
            :label="t('authority.common.operation')" 
            width="120" 
            fixed="right" 
            align="center"
            class-name="operation-column"
          >
            <template #default="scope">
              <div class="operation-buttons">
                <el-button 
                  link 
                  type="primary" 
                  v-if="hasPermission('sys:suborganization:update') || isSuperAdmin"
                  @click="handleModify(scope.row)"
                >
                  {{ t('authority.common.modify') }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50,100]"
            layout="total, prev, pager, next, sizes, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </PageState>
    </div>

    <!-- 组织表单对话框组件 -->
    <org-form-dialog v-if="drawerVisible" v-model:visible="drawerVisible" :form-data="formData"
      :dialog-type="dialogType" @submit-success="handleDrawerSuccess" />

    <!-- 禁用/启用组织对话框 -->
    <status-dialog v-model:visible="statusDialogVisible" :org-name="currentOrgName" :action="currentAction"
      @confirm="confirmToggleStatus" />
  </div>
</template>

<script lang="ts" setup>
// 下级组织管理页（Subordinate Organization）
// 职责：
// - 查询/分页展示下级组织
// - 新增/编辑组织信息（抽屉）
// - 状态切换等操作（确认框）
// - 依据权限控制按钮可见性
import { ref, reactive, onMounted, defineAsyncComponent, computed } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getOrganizationList,
  addOrganization,
  updateOrganization,
} from "./data";
import { useI18n } from "@/composables/useI18n";
import { useAppStore } from "@/store";
import { usePermission } from "@/composables/usePermission";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";

const OrgFormDialog = defineAsyncComponent(() => import("./components/OrgFormDialog.vue"));
const StatusDialog = defineAsyncComponent(() => import("./components/StatusDialog.vue"));

// 多语言
const { t } = useI18n();

// 当前登录用户（用于限定只看自身下级组织）
const appStore = useAppStore();
// 权限
const { hasPermission, isSuperAdmin } = usePermission();

// 搜索参数
const searchParams = reactive({
  organizationName: ""
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const errorMessage = ref("");

// 表头样式：与设计稿一致的浅灰背景
const headerCellStyle = () => ({
  background: '#F5F6FA',
  color: '#111827',
  fontWeight: 600
});

// 抽屉控制
const drawerVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formData = ref({});

// 状态切换对话框
const statusDialogVisible = ref(false);
const currentOrg = ref<any>(null);
const currentOrgName = ref("");
const currentAction = ref("");

// 初始化
onMounted(() => {
  loadTableData();
});

// 加载表格数据：构造查询参数并附带数据权限
const loadTableData = async () => {
  loading.value = true;
  try {
    const currentUser = appStore.state.user;
    const queryParams: any = {
      page: currentPage.value,
      limit: pageSize.value,
      organizationName: searchParams.organizationName
    };

    // 添加组织权限过滤 - 只显示当前用户所在组织的下级组织
    if (currentUser && currentUser.deptId) {
      queryParams.parentId = currentUser.deptId;
    }

    const result = await getOrganizationList(queryParams);

    // 处理数据，确保字段存在
    tableData.value = result.list.map((item: any) => ({
      ...item,
      organizationName: item.organizationName || '-',
      countryRegion: item.countryRegion || '-',
      organizationEmail: item.organizationEmail || '-',
      organizationType: item.organizationType || 0,
      adminName: item.adminName || '-',
      createTime: item.createTime || item.createDate || '-',
      modifyTime: item.modifyTime || item.updateDate || '-',
      modifyUser: item.modifyUser || '-'
    }));
    
    total.value = result.totalCount;
  } catch (error) {
    console.error('加载组织数据失败:', error);
    ElMessage.error('加载组织数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索：重置到第 1 页并重新加载
const handleSearch = () => {
  currentPage.value = 1;
  loadTableData();
};

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  handleSearch();
}, 500, { leading: false, trailing: true });

// 分页：修改每页条数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadTableData();
};

// 分页：跳转页码
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadTableData();
};

// 添加组织：打开抽屉
const handleAddOrg = () => {
  // if (!canCreateOrganization.value) {
  //   // 双重防护：按钮已禁用，这里再防住意外触发
  //   ElMessage.warning(t('messages.operationNotAllowed') || 'No permission to create sub organization');
  //   return;
  // }
  dialogType.value = "add";
  formData.value = {};
  drawerVisible.value = true;
};

// 修改组织：打开抽屉并回填数据
const handleModify = async (row: any) => {
  console.log('修改组织数据:', row); // 调试日志
  dialogType.value = "edit";
  formData.value = { ...row };
  drawerVisible.value = true;
};

// 删除组织
// const handleDelete = async (row: any) => {
//   try {
//     await ElMessageBox.confirm(
//       `确定要删除组织 "${row.organizationName}" 吗？`,
//       "确认删除",
//       {
//         confirmButtonText: "确定",
//         cancelButtonText: "取消",
//         type: "warning"
//       }
//     );

//     const result = await deleteOrganization([row.id]);
//     if (result.success) {
//       ElMessage.success(result.message);
//       loadTableData();
//     } else {
//       ElMessage.error(result.message);
//     }
//   } catch (error) {
//     if (error !== "cancel") {
//       console.error('删除组织失败:', error);
//       ElMessage.error('删除组织失败');
//     }
//   }
// };

// 组织抽屉提交成功回调
const handleDrawerSuccess = async (formData: any) => {
  try {
    if (formData.isAdd) {
      // 添加 - 移除 isAdd 字段
      const { isAdd, ...addData } = formData;
      const result = await addOrganization(addData);
      if (result.success) {
        ElMessage.success(result.message);
      } else {
        ElMessage.error(result.message);
      }
    } else {
      // 更新 - 移除 isAdd 字段
      const { isAdd, ...updateData } = formData;
      const result = await updateOrganization(updateData);
      if (result.success) {
        ElMessage.success(result.message);
      } else {
        ElMessage.error(result.message);
      }
    }

    drawerVisible.value = false;
    loadTableData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 确认切换状态：演示状态切换并调用更新接口
const confirmToggleStatus = () => {
  if (currentOrg.value) {
    currentOrg.value.status = !currentOrg.value.status;

    ElMessage({
      type: "success",
      message: `Organization "${currentOrg.value.name}" has been ${currentAction.value}d`
    });

    // 更新组织状态
    updateOrganization(currentOrg.value);
    currentOrg.value = null;
  }
};

// 重试加载
const retryFetch = () => {
  errorMessage.value = "";
  loadTableData();
};
</script>

<style lang="scss" scoped>
.subordinate-organization-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-container {
  flex-shrink: 0;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
}

/* 表格样式 - 与设计稿一致 */
.adaptive-table {
  // 设置表格布局为自动，实现完全自适应
  :deep(.el-table) {
    table-layout: auto;
    --el-table-border-color: #E5E7EB; // 全局分隔线颜色
  }
  
  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  // 表头：统一浅灰背景，深色文字，加粗，圆角
  :deep(.el-table__header-wrapper),
  :deep(.el-table__header-wrapper th),
  :deep(.el-table__header-wrapper tr),
  :deep(.el-table__header-wrapper .cell),
  :deep(.el-table__header-wrapper thead),
  :deep(.el-table__header-wrapper thead tr),
  :deep(.el-table__header-wrapper thead tr th) {
    background-color: #F5F6FA !important;
    color: #111827 !important;
    font-weight: 600;
    border-bottom: 1px solid #E5E7EB !important;
    padding: 10px 16px;
  }
  
  // 表头左右圆角
  :deep(.el-table__header-wrapper thead tr th:first-child) {
    border-top-left-radius: 8px;
  }
  :deep(.el-table__header-wrapper thead tr th:last-child) {
    border-top-right-radius: 8px;
  }
  
  // 顶部细线颜色
  :deep(.el-table__inner-wrapper::before) {
    background-color: #E5E7EB !important;
    height: 1px;
  }

  // 表体：白底，文字颜色，底部分隔线，内边距
  :deep(.el-table__body tr),
  :deep(.el-table__body td) {
    background-color: #ffffff !important;
  }
  
  :deep(.el-table__body .el-table__cell) {
    color: #374151;
    padding: 12px 16px;
    border-bottom: 1px solid #E5E7EB !important;
  }
  
  // 行 hover 效果
  :deep(.el-table__body tr:hover > td) {
    background: #F9FAFB !important;
  }
  
  // 数据列完全自适应宽度
  :deep(.data-column) {
    .cell {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: keep-all;
    }
  }
  
  // 操作列固定样式，确保始终在右侧
  :deep(.operation-column) {
    position: sticky;
    right: 0;
    z-index: 2;
    background-color: var(--el-table-bg-color);
    
    .cell {
      white-space: nowrap;
      overflow: hidden;
    }
  }
  
  // 操作按钮容器 - 链接风格
  .operation-buttons {
    display: flex;
    gap: 0;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      flex-shrink: 0;
      min-width: auto;
      padding: 0 0; // 看起来像纯文本链接
      font-size: 13px;
      color: #0F766E; // 链接主色
    }
    
    .el-button:hover {
      color: #115E59;
      text-decoration: underline;
      background: transparent;
    }
    
    // 分隔竖线
    .el-button:not(:last-child)::after {
      content: "|";
      display: inline-block;
      margin: 0 10px;
      color: #6B7280; // 更深的灰色，更容易看见
    }
  }
  
  // 确保固定列在斑马纹表格中也有正确的背景色
  :deep(.el-table__row:nth-child(even)) {
    .operation-column {
      background-color: var(--el-table-row-hover-bg-color);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .adaptive-table {
    :deep(.el-table__body-wrapper) {
      overflow-x: auto;
    }
    
    .operation-buttons {
      flex-direction: column;
      gap: 4px;
      
      .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>
